﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CodeRazor
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 2) {
                PrintUsage();
                Environment.Exit(1);
            }

            switch (args[0].ToUpperInvariant())
            {
                case "-FILES":
                    ParseFiles(args.Skip(1));
                    break;
                case "-PROJECTS":
                    ParseProjects(args.Skip(1));
                    break;
                default:
                    PrintUsage();
                    Environment.Exit(2);
                    break;
            }
        }

        static void ParseFiles(IEnumerable<string> fileNames)
        {
            var generator = new CodeGenerator();

            foreach (var fileName in fileNames)
            {
                try
                {
                    var file = new FileInfo(fileName);
                    generator.ParseToFile(new FileInfo(fileName));
                    Console.WriteLine("Generated '{0}'", file.FullName);
                }
                catch (Exception ex)
                {
                    Error(ex.Message);
                }
            }
        }

        static void ParseProjects(IEnumerable<string> projectNames)
        {
            var generator = new CodeGenerator();

            foreach (var projectName in projectNames)
            {
                try
                {
                    generator.ParseProject(projectName);
                    Console.WriteLine("Parsed projects '{0}'", projectName);
                }
                catch (Exception ex)
                {
                    Error(ex.Message);
                }
            }
        }

        static void PrintUsage()
        {
            Console.WriteLine("CodeMyRazor -files FileName1 [FileName2] [FileName3] ... [FileNameN]");
            Console.WriteLine("CodeMyRazor -projects Project1 [Project2] [Project3] ... [ProjectN]");
        }

        static void Error(string message, params object[] args)
        {
            ConsoleColor originalColor = Console.ForegroundColor;
            try
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Error.WriteLine(message, args);
            }
            finally
            {
                Console.ForegroundColor = originalColor;
            }
        }
    }
}
